import { request } from '@/utils/request'
import type { ApiResponse } from '@/types/common'

export interface ChatMessage {
  role: 'user' | 'assistant'
  content: string
}

export interface ChatRequest {
  message: string
  history?: ChatMessage[]
}

export interface ChatResponse {
  reply: string
  conversationId?: string
}

/**
 * AI助手API
 */
export const aiApi = {
  /**
   * 发送聊天消息（普通模式）
   */
  chat(data: ChatRequest): Promise<ApiResponse<ChatResponse>> {
    return request.post('/ai/chat', data)
  },

  /**
   * 流式聊天（使用SSE）
   */
  streamChat(data: ChatRequest, onMessage: (chunk: string) => void, onError?: (error: Error) => void, onDone?: () => void): EventSource {
    const baseURL = '/api'
    const url = `${baseURL}/ai/stream-chat`
    
    // 创建一个隐藏的POST请求来发起SSE
    const eventSource = new EventSource(url)
    
    // 使用fetch发送POST请求
    fetch(url, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify(data)
    }).then(response => {
      if (!response.ok) {
        throw new Error('Network response was not ok')
      }
      
      const reader = response.body?.getReader()
      const decoder = new TextDecoder()
      
      function read(): any {
        return reader?.read().then(({ done, value }) => {
          if (done) {
            onDone?.()
            return
          }
          
          const text = decoder.decode(value, { stream: true })
          const lines = text.split('\n')
          
          for (const line of lines) {
            if (line.startsWith('data: ')) {
              const data = line.substring(6).trim()
              if (data === '[DONE]') {
                onDone?.()
                return
              }
              if (data) {
                try {
                  onMessage(data)
                } catch (e) {
                  console.error('解析SSE数据失败:', e)
                }
              }
            }
          }
          
          return read()
        })
      }
      
      return read()
    }).catch(error => {
      onError?.(error)
    })
    
    return eventSource
  },

  /**
   * 清除对话历史
   */
  clearHistory(): Promise<ApiResponse<void>> {
    return request.post('/ai/clear-history')
  }
}

